import React from 'react'
import NavMenu from './common/nav-menu'
import {Col, Input, Row, Switch, Table} from 'antd'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import {addPublisher, deletePublisher, getPublishers, getUserByNameOrEmail} from '../actions/publisher'

const Search = Input.Search

class PublisherManagementBody extends React.Component {
   columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '是否成为发布者',
      dataIndex: 'isPublisher',
      key: 'isPublisher',
      render: (text, record) => (
        <Switch
          onChange={this.handleRoleChange.bind(this, record.id)}
          checked={text}
        />
      )
    }
  ]

  state = {
    userNameOrEmail: ''
  }
  componentDidMount () {
    this.props.getPublishers()
  }

  onChangeSearchText = (e) => {
    this.setState({ userNameOrEmail: e.target.value})
  }

  onSearch = (value) => {
    this.props.getUserByNameOrEmail(value)
  }

  handleRoleChange = (id,checked) => {
     console.log(checked)
     checked
       ? this.props.addPublisher(id,this.state.userNameOrEmail)
       : this.props.deletePublisher(id,this.state.userNameOrEmail)
  }

  render () {
    const {publishers} = this.props
    return <div>
      <NavMenu />
      <Row>
        <Col span={6}>
          <Search
            placeholder='请输入用户名/邮箱'
            onChange={this.onChangeSearchText}
            onSearch={value => this.onSearch(value)} enterButton />
        </Col>
      </Row>
      <Table dataSource={publishers} columns={this.columns} className='margin-t-2' />
    </div>
  }
}

const mapStateToProps = ({publishers}) => ({
  publishers,
})

const mapDispatchToProps = dispatch => ({
  getPublishers: () => dispatch(getPublishers()),
  getUserByNameOrEmail : (userNameOrEmail) => dispatch(getUserByNameOrEmail(userNameOrEmail)),
  addPublisher: (publisherId,userNameOrEmail) => dispatch(addPublisher(publisherId,userNameOrEmail)),
  deletePublisher: (publisherId, userNameOrEmail) => dispatch(deletePublisher(publisherId, userNameOrEmail))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PublisherManagementBody))
